package com.sell.service.impl;

import com.sell.exception.SellException;
import com.sell.service.RedisLock;
import com.sell.service.SecKillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: lichujun
 * @date: 2018-08-26
 */
@Service
public class SecKillServiceImpl implements SecKillService {

    @Autowired
    private RedisLock lock;

    private static Map<String, Integer> productInfo;

    private static Map<String, Integer> stock;

    private static Map<String, Integer> orders;

    private static final long EXPIRED_TIME = 30 * 1000L;

    static {
        productInfo = new HashMap<>();
        orders = new HashMap<>();
        stock = new HashMap<>();
        productInfo.put("123456", 10000);
        stock.put("123456", 10000);
    }

    @Override
    public String query(String productId) {
        return "商品秒杀，秒杀数量=" +
                productInfo.get(productId) +
                "\n商品剩余数量=" +
                stock.get(productId) +
                "\n商品下单数量=" +
                orders.get(productId)
                ;
    }

    @Override
    public String order(String productId) {
        long time = System.currentTimeMillis() + EXPIRED_TIME;
        if (!lock.lock(productId, String.valueOf(time))) {
            throw new SellException(101, "哎哟喂，没抢到...");
        }
        Integer stockNum = stock.get(productId);
        if (stockNum == 0) {
            throw new SellException(100, "秒杀活动已经结束");
        } else {
            stock.put(productId, stockNum - 1);
            orders.put(productId, orders.get(productId) == null ?1:orders.get(productId)+1);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        lock.unlock(productId, String.valueOf(time));
        return query(productId);
    }
}
